<template>
    <el-dialog v-model="quotation" draggable title="Add to Quotation" width="79%"
        style="position: absolute;top:-80px;left:0;right:0; height:85vh">
        <div class="flex addQuotation">
            <div class="flex fdc addLeft">
                <div class="brs bs pt-10  pl-10 pr-10 ">
                    <el-select v-model="PI_name" filterable @input="OrderCapture" @visible-change="visible"
                        @change="orderChange" style="width: 25%;" placeholder="Please select the order">
                        <el-option v-for="item in orderList" :key="item.PI_name" :label="item.PI_name"
                            :value="item.order_id" />
                    </el-select>
                    <div class="flex jc-sb mt-10">
                        <p class="mt-10 f18">Add items to order</p>
                        <el-button type="primary" plain class="add" @click="add">Add</el-button>
                    </div>
                    <el-table ref="multipleTableRef" :data="quotationTable" @row-click="graph" height="36vh"
                        style="width: 100%;" @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="30" />
                        <el-table-column property="product_name_pi" align="center" label="MODEL" min-width="140" />
                        <el-table-column property="Brand_name" align="center" label="BRAND" />
                        <el-table-column property="quantity" align="center" label="Qty" />
                        <el-table-column prop="price" align="center" label="PRICE" />
                        <el-table-column property="leadingtime" align="center" label="LEADING" />
                        <el-table-column property="product_condition" align="center" label="CONDITION"
                            min-width="120" />
                    </el-table>
                </div>
                <div ref="price" class="w100p mt-10 brs bs pt-10 pb-10 pl-10 pr-10" style="height: 29vh;"></div>
            </div>

            <!-- 右边 -->
            <div class="rightPrice">
                <div class="bs brs pt-10 pl-10 pr-10">
                    <div class="flex jc-e ">
                        <div class="flex jc-e">
                            <el-button plain @click="Added">New</el-button>
                            <el-button type="primary" plain @click="save">Save</el-button>
                            <el-button type="primary" @click="delGoods">Delete</el-button>
                            <el-select v-model="profit" @change="unifiedProfit" class="ml-10 w20p" placeholder="Profit">
                                <el-option v-for="item in profitArr" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                            <el-select v-model="leading" @change="unifiedLeading" class="ml-10 w20p"
                                placeholder="Bulk selection pointer">
                                <el-option v-for="item in newLeading" :key="item.label" :label="item.label"
                                    :value="item.label" />
                            </el-select>
                        </div>
                    </div>

                    <!--表格 -->
                    <div class="mt-1 w100p">
                        <el-table :data="production_item" @cell-click="table" @row-click="row" @cell-mouse-enter="hover"
                            @selection-change="rightSelection" height="40.5vh" style="width: 100%">
                            <el-table-column type="selection" width="35" />
                            <el-table-column label="MODEL" min-width="200">
                                <template v-slot="model">
                                    <el-select v-model="model.row.product.model" @input="getModel" @change="changeModel"
                                        @visible-change="visible" filterable placeholder="MODEL">
                                        <el-option v-for="item in newModel" :key="item.id" :label="item.label"
                                            :value="item.id" />
                                    </el-select>
                                </template>
                            </el-table-column>

                            <el-table-column label="BRAND" min-width="130">
                                <template v-slot="brand">
                                    <el-select v-model="brand.row.brand.brand_name" @input="getBrand"
                                        @visible-change="visible" filterable placeholder="BRAND">
                                        <el-option v-for="item in newBrand" :key="item.id" :label="item.label"
                                            :value="item.id" />
                                    </el-select>
                                </template>
                            </el-table-column>

                            <!-- 采购 -->
                            <el-table-column label="BUYER" min-width="170">
                                <template v-slot="buyer">
                                    <el-select v-model="buyer.row.purchaser_id_list" @remove-tag="delBuyer"
                                        @visible-change="getBuyer" collapse-tags collapse-tags-tooltip
                                        placeholder="BUYER" multiple>
                                        <el-option v-for="item in newBuyer" :key="item.label" :label="item.label"
                                            :value="item.id" />
                                    </el-select>
                                </template>
                            </el-table-column>

                            <!-- 数量 -->
                            <el-table-column label="QTY" min-width="80">
                                <template v-slot="qty">
                                    <el-input v-model="qty.row.Qty" placeholder="QTY" />
                                </template>
                            </el-table-column>
                            <!-- 售出价 -->
                            <el-table-column align="center" label="PRICE" min-width="100">
                                <template v-slot="price">
                                    <el-input v-model="price.row.item.quotation_price"
                                        @input="inpPrice($event, price.row.item.purchase_price, price.row.item)" />
                                </template>
                            </el-table-column>

                            <!-- 利润 -->
                            <el-table-column align="center" label="Profit" min-width="95">
                                <template v-slot="profit">
                                    <div class="flex aic">
                                        <el-input v-model="profit.row.item.profit_rate"
                                            @input="newSale($event, profit.row.item.purchase_price, profit.row.item)" />
                                        <p class="f18">%</p>
                                    </div>
                                </template>
                            </el-table-column>
                            <!-- 成本价 -->
                            <el-table-column align="center" label="COST" min-width="80">
                                <template v-slot="cost">
                                    <el-input v-model="cost.row.item.purchase_price"
                                        @input="inpCost($event, cost.row.item.profit_rate, cost.row.item)" />
                                </template>
                            </el-table-column>
                            <el-table-column label="LEADING" min-width="120">
                                <template v-slot="leading">
                                    <el-select v-model="leading.row.item.leadingtime" filterable placeholder="LEADING">
                                        <el-option v-for="item in newLeading" :key="item.label" :label="item.label"
                                            :value="item.case" />
                                    </el-select>
                                </template>
                            </el-table-column>

                            <el-table-column label="CONDITION" min-width="150">
                                <template v-slot="condition">
                                    <el-select v-model="condition.row.item.product_condition" filterable
                                        placeholder="CONDITION">
                                        <el-option v-for="item in newCondition" :key="item.label" :label="item.label"
                                            :value="item.case" />
                                    </el-select>
                                </template>
                            </el-table-column>

                            <!-- <el-table-column align="right">
                            <template v-slot="del">
                                <el-button size="small" type="primary" @click="delGoods(del.row)">Delete</el-button>
                            </template>
                        </el-table-column> -->
                        </el-table>
                    </div>
                </div>

                <!-- 历史的供应商 -->
                <div class="brs bs mt-10 pt-10 pl-10 pr-10 ">
                    <p class="fwb fa5">Histroy RFQ</p>
                    <el-table :data="historyRfo" height="26vh" style="width: 100%">
                        <el-table-column type="expand">
                            <template #default="props">
                                <div m="4">
                                    <el-table :data="props.row.inquiryItemInfo" border>
                                        <el-tbble-column align="center" prop="dco" label="DCO"></el-tbble-column>
                                        <el-table-column align="center" prop="Qty" label="Qty" />
                                        <el-table-column align="center" prop="item.quotation_price" label="PRICE" />
                                        <el-table-column align="center" prop="item.profit" label="Profit" />
                                        <el-table-column align="center" prop="item.purchase_price" label="COST" />
                                        <el-table-column align="center" prop="leading" label="LEADING">
                                            <template v-slot="leading">
                                                <el-select v-model="leading.row.item.leadingtime" filterable disabled
                                                    placeholder="Select">
                                                    <el-option v-for="item in newLeading" :key="item.label"
                                                        :label="item.label" :value="item.case" />
                                                </el-select>
                                            </template>
                                        </el-table-column>
                                        <!-- <el-table-column align="center" prop="sta" label="STA" /> -->
                                    </el-table>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="inquiry_id" align="center" label="RFQ ID" min-width="140" />
                        <el-table-column prop="country.name" align="center" label="CNTY" />
                        <el-table-column prop="items_count" align="center" label="ITEMS" />
                        <el-table-column prop="customer.Customer_type" align="center" label="SUPPLIER" min-width="90" />
                        <el-table-column prop="state" align="center" label="STA" />
                    </el-table>
                </div>
            </div>
        </div>
    </el-dialog>
</template>

<script setup>
import { ref, nextTick } from 'vue'
import * as $axios from '../../../../api/index'
import * as echarts from "echarts";
import { ElMessage } from 'element-plus'
import { useDemoStore } from '../../../../pinia/index'
const store = useDemoStore()

// 接收父元素传过来的值
const props = defineProps({
    newLeading: Array,
    newCondition: Array
})

// 选择器打开关闭的时候触发
const visible = () => {
    inpBrand.value = '' //清空输入框
    textBrand.value = ''
    inpModel.value = ''
    OrderCapture()
}

// 获取订单列表
const PI_name = ref('')
const orderList = ref([])
const inpBrand = ref()
const OrderCapture = (text) => {
    if (text) {
        if (text.data != null) {
            inpBrand.value += text.data
        } else if (text.data == null) {
            inpBrand.value = inpBrand.value.slice(0, -1)
        }
    }
    const data = {
        token: store.token,
        keywords: inpBrand.value || ''
    }
    $axios.$orderOrder_list(data).then(res => {
        orderList.value = res.data.data
        getBuyer() //触发getBuyer事件把采购id变成采购名
        console.log(res.data.data)
    })
}

// 选择器选项值方式改变时触发
const newOrder_id = ref('')
const quotationTable = ref([]) // 获取报价信息
const production_item = ref([])
const orderId = ref('')
const orderChange = (id) => {
    orderId.value = id || orderId.value
    const data = {
        token: store.token,
        order_id: id || orderId.value
    }
    $axios.$orderOrder_info(data).then(res => {
        quotationTable.value = res.data.itemOrder
        production_item.value = res.data.inquiryItem
        newOrder_id.value = res.data.order_id
        // console.log(newOrder_id.value)
        profit.value = ''  //清空批量利润选择框
        leading.value = ''
        changeModel()
        product_id.value = quotationTable.value[0] && quotationTable.value[0].product_id //拿数组的第一个product_id
        model.value = quotationTable.value[0] && quotationTable.value[0].product_name_pi
        getHistory_quotation() //调用折线图
        getHistoryRfo()  // 调用右边历史询盘表格
    })
}

// 图表
const price = ref()

// 弹窗
const quotation = ref(false)
const poseQuotation = () => {
    quotation.value = true
    // production_item.value = [] //清空数组
    nextTick(() => {
        quote()
    })
}


// 左边多选框
const inquiry = ref([])
const order_id = ref('')
const handleSelectionChange = (data) => {
    inquiry.value = data.map(item => {
        return item.order_info_id
    })
    console.log(data)
    data.forEach(item => {
        order_id.value = item.order_id
    })
}

// 点击左边table
const product_id = ref('')
const model = ref('') //图表标题
const graph = (data) => {
    // console.log(data.product_id)
    product_id.value = data.product_id
    model.value = data.product_name_pi
    getHistory_quotation()
    getHistoryRfo()
}

// 折线图数据
const history_quotation = ref([])
const getHistory_quotation = () => {
    const data = {
        token: store.token,
        product_id: product_id.value
    }
    $axios.$history_quotation(data).then(res => {
        history_quotation.value = res.data
        quote()
    })
}

// 右边历史询盘表格
const historyRfo = ref([])
const getHistoryRfo = () => {
    const data = {
        token: store.token,
        product_id: product_id.value
    }
    $axios.$pollingInquiry_history(data).then(res => {
        console.log(res)
        historyRfo.value = res.data.data
    })
}

// 添加到右边
const add = () => {
    const data = {
        token: store.token,
        order_id: order_id.value,
        order_info_id: inquiry.value
    }
    $axios.$orderOrder_product(data).then(res => {
        production_item.value.pop()
        production_item.value = [
            ...production_item.value,
            ...res.data
        ]
        production_item.value.push({
            "Qty": '',
            "msg": 1,
            "product": {
                "model": ''
            },
            "purchaser_array": {

            },
            "brand": {
                "brand_name": "",
                "filter": "",
            },
            "item": {
                "leadingtime": "",
            }
        })
        // console.log(res.data)
    })
}

const table = (data) => {
    console.log(data)
}

// 删除采购
const delBuyer = (p) => {
    const name = array.value.map(item => {
        return item.id
    })
    // console.log(name)
    const index = name.indexOf(p)
    const data = {
        token: store.token,
        inquiry_item_info_id: array.value[index].inquiry_item_info_id
    }
    $axios.$pollingDel(data).then(res => {
        array.value.splice(index, 1)
        // emits('del')
        // console.log(res.Status)
        // ElMessage({
        //     message: 'successfully delete',
        //     type: 'success',
        // })
    })
}

// table 鼠标经过时触发的
const array = ref([])
const hover = (data) => {
    array.value = data.purchaser_array
}


// model
const newModel = ref([])
const inpModel = ref('')
var timer
const getModel = (text) => {
    if (text.data != null) {
        inpModel.value += text.data
    } else if (text.data == null) {
        inpModel.value = inpModel.value.slice(0, -1)
    }
    const data = {
        token: store.token,
        keywords: inpModel.value
    }
    clearTimeout(timer);
    timer = setTimeout(() => {
        $axios.$product_find(data).then(res => {
            console.log(res.data)
            newModel.value = res.data.map(item => {
                return {
                    'label': item.model,
                    'id': item.product_id
                }
            })
        })
    }, 300)
}

// brand
const newBrand = ref([])
const textBrand = ref('')
var timer
const getBrand = (text) => {
    if (text.data != null) {
        textBrand.value += text.data
    } else if (text.data == null) {
        textBrand.value = textBrand.value.slice(0, -1)
    }
    const data = {
        token: store.token,
        keywords: textBrand.value
    }
    clearTimeout(timer);
    timer = setTimeout(() => {
        $axios.$product_brand(data).then(res => {
            console.log(res.data)
            newBrand.value = res.data.map(item => {
                return {
                    'label': item.brand_name,
                    'id': item.brand_id
                }
            })
        })
    }, 300)
    console.log(inpBrand.value)
}

//Buyer(获取销售与采购人员列表)
const newBuyer = ref([''])
const getBuyer = () => {
    const data = {
        token: store.token,
        keywords: '采购'
    }
    $axios.$userUser_list(data).then(res => {
        newBuyer.value = res.data.map(item => {
            return {
                'label': item.name,
                'id': item.id
            }
        })
        // console.log(res.data)
    })
}


// 利润数据
const profit = ref('')
const profitArr = ref([
    {
        label: '10%',
        value: 10
    },
    {
        label: '15%',
        value: 15
    },
    {
        label: '20%',
        value: 20
    },
    {
        label: '25%',
        value: 25
    },
    {
        label: '30%',
        value: 30
    },
    {
        label: '35%',
        value: 35
    },
    {
        label: '40%',
        value: 40
    },
    {
        label: '45%',
        value: 45
    },
    {
        label: '50%',
        value: 50
    },
])

// 批量更改利润
const unifiedProfit = (data) => {
    production_item.value.forEach(item => {
        if (item.item.quotation_price && item.item.purchase_price) {
            item.item.profit_rate = data
            item.item.quotation_price = ((data / 100) * (item.item.purchase_price || 0 * 1) + (item.item.purchase_price || 0) * 1).toFixed(2)
        }
        console.log(item)
    })
}


// 批量更改指标
const leading = ref('')
const unifiedLeading = (data) => {
    production_item.value.forEach(item => {
        if (item.product.model) {
            item.item.leadingtime = data
        }
        // console.log(item)
    })
}



// 获取利润，计算售出价
const getprofit = ref(0)
const newSale = (e, value, data) => {  //获取利润
    getprofit.value = ((e / 100) * (value || 0 * 1) + (value || 0) * 1).toFixed(2)   //计算售出价
    data.quotation_price = getprofit.value
}

// 获取售出价,计算利润
const newProfit = ref()  //利润
const inpPrice = (e, value, data) => {
    newProfit.value = ((e - value * 1) / value * 1 * 100).toFixed(2)  //计算利润比
    data.profit_rate = newProfit.value == 'NaN' ? 0 : newProfit.value
}


// 获取成本价,计算售出价
const tmoney = ref(0)  //售出价
const inpCost = (e, value, data) => {
    tmoney.value = (e * ((value || 0) / 100) + e * 1).toFixed(2)  //计算售出价
    data.quotation_price = tmoney.value
}



// 新增
const Added = () => {
    if (!!newOrder_id.value) {
        production_item.value = []
        for (let i = 0; i <= 5; i++) {
            production_item.value.push({
                "Qty": '',
                "msg": 1,
                "product": {
                },
                "purchaser_array": {

                },
                "brand": {
                    "brand_name": "",
                    "filter": "",
                },
                "item": {
                    "leadingtime": "",
                }
            })
        }
    } else {
        ElMessage({
            duration: 2000,
            message: 'Please select the order',
            type: 'warning',
        })
    }
}

// 判断输入框是否为空，不为空就添加一个空的输入框
const changeModel = () => {
    // console.log(production_item.value[production_item.value.length-1])
    const model = production_item.value[production_item.value.length - 1] && production_item.value[production_item.value.length - 1].product.model
    const addModel = production_item.value[production_item.value.length - 1]
    if (model || addModel == undefined) {
        production_item.value.push({
            "Qty": '',
            "product": {
            },
            "purchaser_array": {

            },
            "brand": {
                "brand_name": "",
                "filter": "",
            },
            "item": {
                "leadingtime": "",
            }
        })
    }
    // console.log(model)
}

// 右边多选框
const inquiryId = ref([])
const rightSelection = (value) => {
    inquiryId.value = []
    value.forEach(item => {
        if (item.product.model) {
            item.purchaser_array.forEach(i => {
                inquiryId.value.push(i.inquiry_item_info_id)
            })
        }
    })
    // console.log(inquiryId.value)
}

// 删除
const delGoods = () => {
    // console.log(inquiryId.value.length > 0)
    if (inquiryId.value.length > 0) {
        const data = {
            token: store.token,
            inquiry_item_info_id: inquiryId.value
        }
        $axios.$pollingDel(data).then(res => {
            orderChange()
            ElMessage({
                message: 'successfully delete',
                type: 'success',
            })
            console.log(res)
        })
    } else {
        ElMessage({
            message: 'Please choose',
            type: 'warning',
        })
    }
}

// 保存
const save = () => {
    const arr = ref([])
    const newArr = ref([])
    production_item.value.forEach((items) => {
        // 判断是否有model有就是要进行提交的
        if (items.product.model) {
            if (items.purchaser_array.length == items.purchaser_id_list.length && items.purchaser_array.length > 0) {  //没有修改
                items.purchaser_array.forEach((name) => {
                    items.inquiry_item_info_id = name.inquiry_item_info_id
                    arr.value.push({
                        ...items,
                        id: name.id
                    })
                    newArr.value = arr.value.map(item => {
                        return {
                            "order_id": newOrder_id.value,
                            "product_id": typeof item.product.model == 'string' ? item.product.product_id : item.product.model,
                            "brand_id": typeof item.brand.brand_name == 'string' ? item.brand.brand_id : item.brand.brand_name,
                            "inquiry_id": item.inquiry_id,
                            "purchaser_id": item.id,
                            "inquiry_item_info_id": item.inquiry_item_info_id || '',
                            'model': item.product.model,
                            'qty': item.Qty,
                            'quotation_price': item.item.quotation_price,
                            'profit_rate': item.item.profit_rate,
                            'price': item.item.purchase_price,
                            'purchase_price': item.item.purchase_price,
                            'leadingtime': item.item.leadingtime || item.leadingtime,
                            'product_condition': item.product_condition || item.item.product_condition,
                        }
                    })
                })
            } else { //有修改
                console.log(2)
                items.purchaser_id_list.forEach((name, index) => {
                    // console.log(items.purchaser_array[index]&&items.purchaser_array[index].id)
                    arr.value.push({
                        ...items,
                        id: name,
                        inquiry_item_info_id: items.purchaser_array[index] && items.purchaser_array[index].inquiry_item_info_id
                    })
                    // console.log(arr.value)

                    newArr.value = arr.value.map(item => {
                        return {
                            "order_id": newOrder_id.value,
                            "product_id": typeof item.product.model == 'string' ? item.product.product_id : item.product.model,
                            "brand_id": typeof item.brand.brand_name == 'string' ? item.brand.brand_id : item.brand.brand_name,
                            "inquiry_id": item.inquiry_id,
                            "purchaser_id": item.id,
                            "inquiry_item_info_id": item.inquiry_item_info_id || '',
                            'model': item.product.model,
                            'qty': item.Qty,
                            'quotation_price': item.item.quotation_price,
                            'profit_rate': item.item.profit_rate,
                            'price': item.item.purchase_price,
                            'purchase_price': item.item.purchase_price,
                            'leadingtime': item.item.leadingtime || item.leadingtime,
                            'product_condition': item.product_condition || item.item.product_condition,
                        }
                    })
                })
            }
        }
    });

    console.log(newArr.value)
    // console.log(production_item.value[0].msg)
    if (production_item.value[0].msg === 1) {    //判断是不是新增的
        // console.log('新增订单转询盘')
        const data = {
            token: store.token,
            product: newArr.value,
        }
        $axios.$quotationNew_quotation(data).then(res => {
            // console.log(res)
            quotation.value = false
            emits('quote') //触发事件，更新页面
            orderChange()
            ElMessage({
                message: 'Successful preservation',
                type: 'success',
            })
        })
    } else {
        const data = {
            token: store.token,
            product: newArr.value,
        }
        $axios.$quotationSave_quotation(data).then(res => {
            // console.log(res)
            orderChange()
            ElMessage({
                message: 'Successful preservation',
                type: 'success',
            })
        })
    }
}

const emits = defineEmits(['quote'])

// 暴露方法
defineExpose({
    poseQuotation
})

// 添加到报价的图表
var myChart
const quote = () => {
    if (myChart != null && myChart != "" && myChart != undefined) {
        myChart.dispose();//销毁
    }
    myChart = echarts.init(price.value, 'westeros');
    var option = {
        title: {
            text: model.value
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                label: {
                    backgroundColor: '#fff'
                }
            }
        },
        legend: {
            data: ['Histroy quotation']
        },
        toolbox: {
            feature: {
                saveAsImage: {}
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [
            {
                type: 'category',
                boundaryGap: false,
                data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
            }
        ],
        yAxis: [
            {
                type: 'value'
            }
        ],
        series: [
            {
                name: 'Histroy quotation',
                type: 'line',
                stack: 'Total',
                areaStyle: {},
                emphasis: {
                    focus: 'series'
                },
                data: history_quotation.value
            }
        ]
    };
    option && myChart.setOption(option);
    window.addEventListener("resize", myChart.resize) //自动缩放
}
</script>

<style lang="less" scoped>
.addQuotation {
    .brs {
        border-radius: 10px;
    }

    .addLeft {
        width: 50%;
        padding-right: 10px;
    }

    .rightPrice {
        // border: 1px solid red;
        width: 50%;
    }

    .add.el-button.is-plain {
        border: 1px solid #7da3f3;
        color: #7da3f3;
        background-color: #ecf5ff;
    }

    .el-button.is-plain {
        border: 1px solid #7da3f3;
        color: #7da3f3;
        background-color: #fff;
    }
}
</style>